local skynet                = require "skynet"
local server_socket 	    = require "skynet.socket"
local client_socket         = require "client.socket"
local proto                 = require "proto.proto"          

local serHost,serRequest
local cliHost,cliRequest
local session = 0

last_tick 
stall_time 

local socket = {}

function socket:create_data()
    
    local socket_data = {
        
         flag = {
             eof       = false, -- 判断是否允许连接标志
             server    = false, -- 判断是否是服务器连接
            },

         client_addr   = '', -- 客户端ip

         type          = '', -- 消息的类型  REQUEST/RESPONSE 两种
         name          = '', -- 调用的函数名        
         response      = 0,  -- 是否有回调的消息函数
         rdata         = '', -- 读取的数据
         rsize         = 0,  -- 读取大小

         wdata         = '', -- 写入数据    
         write         = 0,  -- 写入大小
         
         rdata_tick    = 0,  -- 最后recv时间(用于检测超时时间);当禁用超时时为零
         --func_recv   = 0,  -- 接收函数
         --func_send   = 0,  -- 发送函数
         func_parse    = 0,  -- 解析函数
         
         session_data  = 0,  -- 储与会话相关的特定于应用程序的数据
    }

    return socket_data
end 

function socket:get_session()
        
    if session >= 0x7FFFFFFF then 

        session = 0
    end 

    session = session + 1
    return session 
end 

-- 协议初始化
function socket:proto_init(num)

 -- 指定 加载协议
    if num then 

        return proto.load(num)
    end

-- 未指定全部加载
    serHost,serRequest = proto.load(proto.GAME_S2C)
--    cliHost,cliRequest = proto.load(proto.GAME_C2S)
end 

-- 返回 false 表示失败
function socket:connect(ip, port)

    if ip and port then    

        local fd = client_socket.connect(ip, port)

        if fd then 
            return fd
        end 
    end

    return false    
end 

function socket:client_send_package(fd, pack)

    local package = string.pack(">s2", pack)
	client_socket.send(fd, package)
end 

-- 发送至client
function socket:send_package(fd, pack)

    local package = string.pack(">s2", pack)
	server_socket.write(fd, package)
end 

function socket:ser_request_package(fd, name, data)
    
    self:send_package(fd, serRequest(name, data, self:get_session())) 
end 


function socket:cli_request_package(fd, name, data)

    self:client_send_package(fd, cliRequest(name, data, self:get_session()))
end 

function socket:ser_host(msg,sz)

    return serHost:dispatch(msg, sz)
end 


function socket:cli_host(msg, sz)

    return cliHost:dispatch(msg, sz)
end 

function socket:do_close(fd)
end 

-- 注册消息体
function socket:register_protocol(Name, Id, Unpack, Dispatch)

    if Name and Id and Unpack and Dispatch then 

        skynet.register_protocol {
        name = Name,
        id  = Id,
        unpack = Unpack,
        dispatch = Dispatch
        }

        return false 
    end 

    return true 
end 


return socket

